/**
 * <p>文件名: SysOutAuthDaoImpl.java</p>
 * <p>版权声明: Copyright &copy; 2012-2013 天健通泰科技</p>
 * <p>创建者: 李数</p>
 * <p>创建时间: 2012-10-22  下午04:24:00</p>
 */
package com.tjtt.tdm.system.dao.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;

import com.tjtt.common.utils.StringUtil;
import com.tjtt.tdm.base.BaseHibernateDao;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.constants.PageState;
import com.tjtt.tdm.system.bean.TdmOutauth;
import com.tjtt.tdm.system.dao.SysOutAuthDao;

/**
 * @author Administrator
 *
 */
public class SysOutAuthDaoImpl extends BaseHibernateDao implements SysOutAuthDao {

	@Override
	public PageResult queryOutauth(Map filterMap) {
		StringBuffer queryString = new StringBuffer();
		StringBuffer queryCountString = new StringBuffer();
		queryCountString.append("SELECT count(*) FROM TDM_OUTAUTH T "+
								" LEFT JOIN sys_users F ON F.USERID = T.FROM_USERID "+
								" LEFT JOIN sys_users TT ON TT.USERID = T.TO_USERID "+
								" WHERE 1 = 1");
		queryString.append("SELECT T.id, "+
						   " F.USERNAME from_user,"+
					       " t.OPERATE_MODULENAME module_name,"+
					       " TT.USERNAME to_user,"+
					       " T.start_date,"+
					       " T.end_date "+
						   " FROM TDM_OUTAUTH T "+
						   " LEFT JOIN sys_users F ON F.USERID = T.FROM_USERID "+
						   " LEFT JOIN sys_users TT ON TT.USERID = T.TO_USERID "+
						   " WHERE 1 = 1");
		if (filterMap!= null && !filterMap.isEmpty()) {
			String filterProperty;
			String filterValue;
			filterProperty = "userId";
			filterValue = (String) filterMap.get(filterProperty);
			//这里查询把数据库和要查询的字符全转成小写
			if (!StringUtil.isMissing(filterValue)) {
				queryString.append(" and T.FROM_USERID =").append(StringUtil.encodingUrl(filterValue));
				queryCountString.append(" and T.FROM_USERID =").append(StringUtil.encodingUrl(filterValue));
			}
			String sidx = (String) filterMap.get("sidx");
			String sord = (String) filterMap.get("sord");
			queryString.append(" order by " + sidx + " " + sord + " ");
		}
		return searchBySQL(queryCountString.toString(), queryString.toString(), filterMap);
	}
	@Override
	public PageResult queryOutauthList(Map filterMap) {
		String userid = ServletActionContext.getRequest().getSession().getAttribute("TDM_USER_ID").toString();
		StringBuffer queryString = new StringBuffer();
		StringBuffer queryCountString = new StringBuffer();
		queryCountString.append("select count(*) "+
								 " from   flow_task t LEFT JOIN CF_TDM f on f.id=t.main_id "+
								 " left join tdm_outauth t1 on t1.flow_id = t.flow_type_id "+
								 " and t.flow_state_id = t1.operate_module_id "+
								 " LEFT JOIN flow_flowtype t2 ON t.flow_type_id = t2.id "+
								 " where t1.to_userid = '"+userid+"'"+
								 " and t.flow_state_id != 'end' "+
								 " and t.flow_state_id != 'finish' "+
								 " and to_char(SYSDATE,'yyyy-MM-dd') >= to_char(t1.start_date,'yyyy-MM-dd') "+
								 " and to_char(SYSDATE,'yyyy-MM-dd') <= to_char(t1.end_date,'yyyy-MM-dd') ");
		queryString.append("select T.ID, "+
						       "T2.FLOWNAME,"+
						       "T.FLOW_NAME,"+
						       "T.FLOW_TYPE_ID,"+
						       "T.FLOW_STATE_ID,"+
						       "T.FLOW_STATE_NAME,"+
						       "T.FLOW_ACTION_TYPE,"+
						       "T.INSTANCE_ID,"+
						       "T.NEXT_ROLES_ID,"+
						       "T.NEXT_ROLES_NAME,"+
						       "T.NEXT_USERS_ID,"+
						       "T.NEXT_USERS_NAME,"+
						       "T.ADD_TIME,"+
						       "T.ADD_USER_ID,"+
						       "T.ADD_USER_NAME,t.shiyanbh "+
							   " from   flow_task t LEFT JOIN CF_TDM f on f.id=t.main_id "+
							   " left join tdm_outauth t1 on t1.flow_id = t.flow_type_id "+
							   " and t.flow_state_id = t1.operate_module_id "+
							   " LEFT JOIN flow_flowtype t2 ON t.flow_type_id = t2.id "+
							   " where t1.to_userid = '"+userid+"'"+
							   " and t.flow_state_id != 'end' "+
							   " and t.flow_state_id != 'finish' "+
							   " and to_char(SYSDATE,'yyyy-MM-dd') >= to_char(t1.start_date,'yyyy-MM-dd') "+
							  " and to_char(SYSDATE,'yyyy-MM-dd') <= to_char(t1.end_date,'yyyy-MM-dd') ");
		if (filterMap!= null && !filterMap.isEmpty()) {
			String filterProperty;
			String filterValue; 
			filterValue = (String)filterMap.get("flowtype");
			if(filterValue != null && !filterValue.isEmpty()){
				queryString.append(" and t2.FLOWNAME like '%").append(filterValue).append("%' ");
				queryCountString.append(" and t2.FLOWNAME like '%").append(filterValue).append("%' ");
			}
			filterValue = (String)filterMap.get("flowname");
			if(filterValue != null && !filterValue.isEmpty()){
				queryString.append(" and t.FLOW_NAME like '%").append(filterValue).append("%' ");
				queryCountString.append(" and t.FLOW_NAME like '%").append(filterValue).append("%' ");
			}
			if(null != filterMap.get("WEITUODANWEI") &&! "".equals(filterMap.get("WEITUODANWEI"))){
				queryString.append(" and f.WEITUODANWEI like '%").append(filterMap.get("WEITUODANWEI")).append("%' ");
				queryCountString.append(" and f.WEITUODANWEI like '%").append(filterMap.get("WEITUODANWEI")).append("%' ");
			}
			if(null != filterMap.get("TEST_NO") &&! "".equals(filterMap.get("TEST_NO"))){
				queryString.append(" and f.TEST_NO like '%").append(filterMap.get("TEST_NO")).append("%' ");
				queryCountString.append(" and f.TEST_NO like '%").append(filterMap.get("TEST_NO")).append("%' ");
			}

			if(filterMap.get("WEITUORIQ")!=null && !"".equals(filterMap.get("WEITUORIQ"))){
				queryString.append(" and f.WEITUORIQ >= '"+filterMap.get("WEITUORIQ")+"'");
				queryCountString.append(" and f.WEITUORIQ >= '"+filterMap.get("WEITUORIQ")+"'");
			}
			if(filterMap.get("WEITUORIQTO")!=null && !"".equals(filterMap.get("WEITUORIQTO"))){
				queryString.append(" and f.WEITUORIQ<= '"+filterMap.get("WEITUORIQTO")+"'");
				queryCountString.append(" and f.WEITUORIQ <= '"+filterMap.get("WEITUORIQTO")+"'");
			}
			String sidx = (String) filterMap.get("sidx");
			String sord = (String) filterMap.get("sord");
			queryString.append(" order by t." + sidx + " " + sord + " ");
		}
		return searchBySQL(queryCountString.toString(), queryString.toString(), filterMap);
	}
	@Override
	public String haveOutauth(String userid) {
		List<TdmOutauth> list = (List<TdmOutauth>)this.getHibernateTemplate().find("from TdmOutauth t where t.fromUserid=" + new BigDecimal(userid));
		String returnStr = "";
		if(list!= null && list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				returnStr += list.get(i).getOperateModuleId() + ",";
			}
		}
		if(!"".equals(returnStr)){
			returnStr = returnStr.substring(0,returnStr.length()-1);
		}
		return returnStr;
	}

	public String[] receiveUser(String userid){
		String[] returnStr = new String[2];
		String sql = "SELECT t.FROM_USERID,t.OPERATE_MODULE_ID"+
					 " FROM TDM_OUTAUTH T"+
					 " WHERE t.TO_USERID="+userid+" AND  SYSDATE> t.START_DATE AND SYSDATE<t.END_DATE";
		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		String receiveIds = "";
		String moduleIds = "";
		if(list!=null && list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				Object[] obj = (Object[])list.get(i);
				receiveIds += "'" + obj[0] + "',";
				moduleIds += obj[1] + ",";
			}
			if(!"".equals(receiveIds)){
				receiveIds = receiveIds.substring(0,receiveIds.length()-1);
			}
			if(!"".equals(moduleIds)){
				moduleIds = moduleIds.substring(0,moduleIds.length()-1);
			}
		}
		returnStr[0] = receiveIds;
		returnStr[1] = moduleIds;
		return returnStr;
	}
	@Override
	public String getModule(String role,String haveModule) {
		String sql = "SELECT DISTINCT M.MODULE_ID,m.MENUNAME"+
					" FROM ROLEMENU T"+
					" LEFT JOIN MENU M"+
					" ON M.MENUID = T.MENUID"+
					" WHERE M.PARENTID = "+ PageState.MENU_WORKFLOW +
					" AND T.ROLEID IN ("+ role +")";
		if(!StringUtil.isEmpty(haveModule)){
			sql+=" AND m.MODULE_ID NOT IN("+ haveModule +")";
		}
		sql += " AND M.MODULE_ID IS NOT NULL";
		sql+= " ORDER BY M.MODULE_ID";
		Query query = this.getSession().createSQLQuery(sql);
		List list = query.list();
		String returnStr = "";
		String[] haved = haveModule.split(",");
		
		if(list!=null && list.size()>0){
			returnStr+="[";
			for (int i = 0; i < list.size(); i++) {
				Object[] obj = (Object[])list.get(i);
//				if(isExist(String.valueOf(obj[0]),haved)){
//					returnStr += "{\"id\":\""+obj[0]+"\",\"name\":\""+obj[1]+"\",\"selected\":\"1\"},";
//				}else{
					returnStr += "{\"id\":\""+obj[0]+"\",\"name\":\""+obj[1]+"\",\"selected\":\"0\"},";
//				}
			}
			returnStr = returnStr.substring(0,returnStr.length()-1)+"]";
		}
		return returnStr;
	}

	public boolean isExist(String id,String[] haved){
		boolean   hasFlag=false; 
		for   (String in :  haved) 
		{ 
		   if   (in.equals(id)) 
		     { 
		       hasFlag=true; 
		       break; 
		      } 
		} 
		return hasFlag;
	}
	@Override
	public String saveOutauth(TdmOutauth auth) {
		String operationModuleId = auth.getOperateModuleId();
		String operateModuleName = auth.getOperateModulename();
		String []operateModuleIds = operationModuleId.split(",");
		String []operateModuleNames = operateModuleName.split(",");
		for(int i = 0;i <operateModuleIds.length;i++){
			TdmOutauth out = new TdmOutauth();
			out.setCreateDate(new Timestamp(System.currentTimeMillis()));
			out.setAuthState(new BigDecimal("0"));
			out.setFlowId(auth.getFlowId());
			out.setFromUserid(auth.getFromUserid());
			out.setToUserid(auth.getToUserid());
			out.setStartDate(auth.getStartDate());
			out.setEndDate(auth.getEndDate());
			out.setOperateModuleId(operateModuleIds[i]);
			out.setOperateModulename(operateModuleNames[i]);
			this.getHibernateTemplate().save(out);
		}
		return null;
	}

	@Override
	public void updateOutauth(TdmOutauth auth) {
		this.getHibernateTemplate().update(auth);
	}
	@Override
	public void deleteOutauth(String ids) {
		String[] idss = ids.split(",");
		for(String id : idss){
			TdmOutauth out = (TdmOutauth)this.getHibernateTemplate().load(TdmOutauth.class, new BigDecimal(id));
			this.getHibernateTemplate().delete(out);
		}
	}

}
